import { ref } from 'vue'

let debounceTimer: number | null = null

/**
 * 防抖Hook
 * @param fn 要执行的函数
 * @param delay 延迟时间(ms)
 */
export function useDebounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
) {
  return (...args: Parameters<T>) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
    debounceTimer = setTimeout(() => {
      fn(...args)
    }, delay) as unknown as number
  }
}

/**
 * 防抖搜索Hook
 * @param searchFn 搜索回调函数
 * @param delay 延迟时间(ms)
 */
export function useSearchDebounce(
  searchFn: (value: string) => void,
  delay: number = 300
) {
  const searchValue = ref('')
  
  const debouncedSearch = useDebounce((value: string) => {
    searchFn(value)
  }, delay)
  
  const handleSearch = (value: string) => {
    searchValue.value = value
    debouncedSearch(value)
  }
  
  return {
    searchValue,
    handleSearch
  }
}
